package com.ts.api.task.log;

import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.module.product.dao.ProductApplyFlowDao;
import com.ts.api.module.product.entity.po.ProductApplyFlowPO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentLinkedDeque;

/**
 *  计划流程日志执行器
 *
 *  @author Pan
 */
@Component
public class ProductFlowApplyLogExecute {

    private static ConcurrentLinkedDeque<ProductApplyFlowPO> FLOW_DEQUE = new ConcurrentLinkedDeque<>();

    @Autowired
    private ProductApplyFlowDao productApplyFlowDao;

    /** 批量长度 */
    private int batchSize = 100;

    public ProductFlowApplyLogExecute() {
        super();
        startFlowBatchInsert();
    }

    /**
     *  流程日志-执行批量插入操作
     */
    void startFlowBatchInsert() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
            List<ProductApplyFlowPO> list = CollUtils.newArrayList();

            Iterator<ProductApplyFlowPO> iterator = FLOW_DEQUE.iterator();
            while (iterator.hasNext()) {
                list.add(iterator.next());
                iterator.remove();
            }

            if (ValidParam.isEmpty(list)) {
                return ;
            }

            if (list.size() > batchSize) {
                CollUtils.batchProcess(list, batchSize, (pageList) -> productApplyFlowDao.batchInsert(pageList));
            } else {
                productApplyFlowDao.batchInsert(list);
            }
            }
        }, 0, 500l);
    }

    /**
     *  异步执行
     */
    public void execute(ProductApplyFlowPO productApplyFlowPO) {
        FLOW_DEQUE.add(productApplyFlowPO);
    }

}
